<template>
  <div class="my-posts-page">
    <!-- 主页面 - 我的帖子列表 -->
    <div class="posts-container" v-if="!showEditor">
      <div class="page-header">
        <h2>我的帖子</h2>
        <div class="header-actions">
        <el-button type="primary" @click="showEditor = true" class="publish-btn">
          <el-icon><Plus /></el-icon>
          发布新帖子
        </el-button>
        </div>
      </div>

      <!-- 帖子列表 -->
      <div class="posts-list" v-if="myPosts.length > 0">
        <MyPostCard 
          v-for="post in myPosts"
          :key="post.id"
          :post="post"
          :currentUser="currentUser"
          @like="handleLike"
          @dislike="handleDislike"
          @toggle-comments="toggleComments"
          @add-comment="addComment"
          @add-reply="addReply"
          @preview-image="previewImage"
          @edit-post="editPost"
          @delete-post="deletePost"
        />
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-else>
        <el-empty description="您还没有发布过帖子" :image-size="200">
          <el-button type="primary" @click="showEditor = true">
            发布第一个帖子
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 发布帖子编辑器 -->
    <PostEditor
      v-else
      :currentUser="currentUser"
      :editPostData="editingPost"
      @close="handleEditorClose"
      @submit="handlePostSubmit"
    />

    <!-- 图片预览对话框 -->
    <el-dialog
      v-model="showImagePreview"
      title="图片预览"
      width="600px"
      align-center
    >
      <div class="image-preview-dialog">
        <img :src="previewImageUrl" alt="预览图片" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import PostEditor from './PostEditor.vue'
import MyPostCard from './MyPostCard.vue'

// 当前用户信息
const currentUser = ref({
  id: 1,
  name: '张大山',
  avatar: 'https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
  type: 'farmer'
})

// 响应式数据
const showEditor = ref(false)
const myPosts = ref([])
const editingPost = ref(null)
const showImagePreview = ref(false)
const previewImageUrl = ref('')

// 初始化示例数据
const initSampleData = () => {
  myPosts.value = [
    {
      id: 1,
      content: '今年的西红柿长势特别好，采用了新的有机种植技术，果实饱满多汁，欢迎大家来参观选购！有机种植不仅让果实更加健康，也让土地得到了更好的保护。我们坚持不使用化学农药和化肥，让每一颗西红柿都充满自然的味道。',
      keywords: ['西红柿', '有机种植', '新鲜', '健康'],
      images: [
        'https://images.unsplash.com/photo-1546470427-e212b7d31075?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
        'https://images.unsplash.com/photo-1515358402579-4d343d4c6c30?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80',
        'https://images.unsplash.com/photo-1592924357228-91a4daadcfea?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80'
      ],
      type: 'farmer',
      privacy: 'public',
      author: currentUser.value,
      createTime: new Date('2024-01-15 10:30:00').toISOString(),
      likes: 24,
      dislikes: 2,
      userAction: 'like',
      showComments: false,
      newComment: '',
      comments: [
        {
          id: 1,
          author: {
            name: '李大妈',
            avatar: 'https://images.unsplash.com/photo-1494790108755-2616b612b786?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
            type: 'buyer'
          },
          content: '看起来真不错！什么价格？想买一些给家人尝尝。',
          time: new Date('2024-01-15 11:00:00').toISOString(),
          replies: [
            {
              id: 2,
              author: currentUser.value,
              content: '您好！我们的有机西红柿价格是15元/斤，量大从优哦！',
              time: new Date('2024-01-15 11:05:00').toISOString()
            }
          ],
          replyText: ''
        },
        {
          id: 3,
          author: {
            name: '王大叔',
            avatar: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
            type: 'buyer'
          },
          content: '支持有机种植！请问可以送货上门吗？',
          time: new Date('2024-01-15 14:20:00').toISOString(),
          replies: [],
          replyText: ''
        }
      ]
    },
    {
      id: 2,
      content: '寻找优质的有机蔬菜供应商，需要长期合作，有稳定供货能力的请联系我。我们餐厅每天需要大量新鲜蔬菜，希望找到可靠的合作伙伴。',
      keywords: ['采购', '有机蔬菜', '长期合作', '餐厅'],
      images: [],
      type: 'buyer',
      privacy: 'public',
      author: currentUser.value,
      createTime: new Date('2024-01-14 15:20:00').toISOString(),
      likes: 8,
      dislikes: 0,
      userAction: null,
      showComments: false,
      newComment: '',
      comments: []
    },
    {
      id: 3,
      content: '分享一个种植小技巧：在种植黄瓜时，适当施用草木灰可以有效预防病虫害，还能提高果实品质。大家有什么好的种植经验也欢迎分享！',
      keywords: ['种植技巧', '黄瓜', '病虫害防治', '经验分享'],
      images: [
        'https://images.unsplash.com/photo-1449300079327-02f967c1cdee?ixlib=rb-1.2.1&auto=format&fit=crop&w=400&q=80'
      ],
      type: 'farmer',
      privacy: 'public',
      author: currentUser.value,
      createTime: new Date('2024-01-13 09:15:00').toISOString(),
      likes: 15,
      dislikes: 1,
      userAction: null,
      showComments: false,
      newComment: '',
      comments: [
        {
          id: 4,
          author: {
            name: '赵大哥',
            avatar: 'https://images.unsplash.com/photo-1500648767791-00dcc994a43e?ixlib=rb-1.2.1&auto=format&fit=crop&w=100&q=80',
            type: 'farmer'
          },
          content: '感谢分享！我也试试这个方法。',
          time: new Date('2024-01-13 10:30:00').toISOString(),
          replies: [],
          replyText: ''
        }
      ]
    }
  ]
}

// 预览图片
const previewImage = (imageUrl) => {
  previewImageUrl.value = imageUrl
  showImagePreview.value = true
}

// 点赞处理
const handleLike = (postId) => {
  const post = myPosts.value.find(p => p.id === postId)
  if (post) {
    if (post.userAction === 'like') {
      // 取消点赞
      post.likes = Math.max(0, post.likes - 1)
      post.userAction = null
    } else {
      // 点赞
      if (post.userAction === 'dislike') {
        post.dislikes = Math.max(0, post.dislikes - 1)
      }
      post.likes++
      post.userAction = 'like'
    }
  }
}

// 点踩处理
const handleDislike = (postId) => {
  const post = myPosts.value.find(p => p.id === postId)
  if (post) {
    if (post.userAction === 'dislike') {
      // 取消点踩
      post.dislikes = Math.max(0, post.dislikes - 1)
      post.userAction = null
    } else {
      // 点踩
      if (post.userAction === 'like') {
        post.likes = Math.max(0, post.likes - 1)
      }
      post.dislikes++
      post.userAction = 'dislike'
    }
  }
}

// 切换评论显示
const toggleComments = (postId) => {
  const post = myPosts.value.find(p => p.id === postId)
  if (post) {
    post.showComments = !post.showComments
  }
}

// 添加评论
const addComment = ({ postId, content, author }) => {
  const post = myPosts.value.find(p => p.id === postId)
  if (post) {
    const newComment = {
      id: Date.now(),
      author: author,
      content: content,
      time: new Date().toISOString(),
      replies: [],
      replyText: ''
    }
    
    if (!post.comments) {
      post.comments = []
    }
    
    post.comments.push(newComment)
    ElMessage.success('评论发布成功')
  }
}

// 添加回复
const addReply = ({ postId, commentId, content, author }) => {
  const post = myPosts.value.find(p => p.id === postId)
  if (post && post.comments) {
    const comment = post.comments.find(c => c.id === commentId)
    if (comment) {
      const newReply = {
        id: Date.now(),
        author: author,
        content: content,
        time: new Date().toISOString()
      }
      
      if (!comment.replies) {
        comment.replies = []
      }
      
      comment.replies.push(newReply)
      ElMessage.success('回复成功')
    }
  }
}

// 编辑帖子
const editPost = (post) => {
  editingPost.value = { ...post }
  showEditor.value = true
}

// 删除帖子
const deletePost = async (post) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个帖子吗？删除后无法恢复。',
      '确认删除',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    myPosts.value = myPosts.value.filter(p => p.id !== post.id)
    ElMessage.success('帖子删除成功')
  } catch (error) {
    // 用户取消删除
  }
}

// 处理编辑器关闭
const handleEditorClose = () => {
  showEditor.value = false
  editingPost.value = null
}

// 处理帖子提交
const handlePostSubmit = (postData) => {
  if (editingPost.value) {
    // 编辑现有帖子
    const index = myPosts.value.findIndex(post => post.id === editingPost.value.id)
    if (index !== -1) {
      myPosts.value[index] = {
        ...myPosts.value[index],
        ...postData,
        id: editingPost.value.id // 保持原有ID
      }
    }
    editingPost.value = null
    ElMessage.success('帖子更新成功')
  } else {
    // 添加新帖子
    const newPost = {
      ...postData,
      id: Date.now(), // 生成新ID
      createTime: new Date().toISOString(),
      likes: 0,
      dislikes: 0,
      userAction: null,
      showComments: false,
      comments: []
    }
    myPosts.value.unshift(newPost)
    ElMessage.success('帖子发布成功')
  }
  
  showEditor.value = false
}

// 组件挂载时初始化数据
onMounted(() => {
  initSampleData()
})
</script>

<style scoped>
.my-posts-page {
  background: #f8f9fa;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  padding: 20px 24px;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.page-header h2 {
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.publish-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 25px;
  padding: 12px 24px;
  font-weight: 600;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
  transition: all 0.3s ease;
}

.publish-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.posts-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 20px;
}

.empty-state {
  max-width: 500px;
  margin: 100px auto;
  text-align: center;
  background: white;
  border-radius: 20px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
}

.image-preview-dialog {
  text-align: center;
}

.image-preview-dialog img {
  max-width: 100%;
  max-height: 400px;
  border-radius: 12px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .my-posts-page {
    padding: 16px;
  }

  .page-header {
    flex-direction: column;
    gap: 20px;
    align-items: stretch;
    text-align: center;
  }

  .page-header h1 {
    font-size: 1.75rem;
  }

  .empty-state {
    margin: 50px auto;
    padding: 30px 20px;
  }
}

@media (max-width: 480px) {
  .my-posts-page {
    padding: 12px;
  }

  .page-header h1 {
    font-size: 1.5rem;
  }

  .publish-btn {
    padding: 10px 20px;
    font-size: 0.9rem;
  }
}
</style>